var passport = require('passport'),
  LocalStrategy = require('passport-local').Strategy,
  bcrypt = require('bcryptjs');

// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function (user, done) {
  // sails.log('serialize user: ' + user.id);
  done(null, {
    id: user.id,
    _isAdmin: user._isAdmin,
    _isCompany: user._isCompany
  });
});

passport.deserializeUser(function (data, done) {
  // sails.log('deserializeUser user: ' + data.id);
  if (data._isAdmin) {
    ApiService.request(ApiConstants.admin_user, {
      urlData: {
        id: data.id
      }
    }, function (data) {
      done(null, data);
    })
  } else if (data._isCompany) {
    ApiService.request(ApiConstants.staff_user, {
      urlData: {
        id: data.id
      }
    }, function (data) {
      done(null, data);
    })
  } else {
    done('deserialize user failed.', null);
  }
});

function loginByCore(url, username, password, done) {
  ApiService.request(url, {
    data: {
      username: username,
      password: password
    }
  }, function (data, response) {
    if (data.code == '-1001') {
      return done(null, false, {
        message: data.message
      });
    } else if (data.code == '200') {
      console.log(data.data);
      // for company
      // { id: 1,
      //   createTime: 1469670762000,
      //   modifyTime: 1469670762000,
      //   username: 'yssh',
      //   aliasName: '企业管理员',
      //   password: '123',
      //   telephone: '123',
      //   admin: true,
      //   companyId: 15 }
      return done(null, data.data, {
        message: 'Logged In Successfully'
      });
    } else {
      return done(null, false, {
        message: "error."
      });
    }
  });
}


// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object.
passport.use(new LocalStrategy({
    passReqToCallback: true,
  },
  function (req, username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {
      // Find the user by username. If there is no user with the given
      // username, or the password is not correct, set the user to `false` to
      // indicate failure and set a flash message. Otherwise, return the
      // authenticated `user`.
      if (req.session.isCompany) {
        loginByCore(ApiConstants.company_login, username, password, function (err, data, msg) {
          data._isCompany = true;
          done(err, data, msg);
        });
        return;
      } else if (req.session.isAdmin) {
        loginByCore(ApiConstants.admin_login, username, password, function (err, data, msg) {
          data._isAdmin = true;
          done(err, data, msg);
        });
        return;
      }
      return done(null, false, {
        message: data.message
      });
    });
  }
));
